package model

import (
	"github.com/BarnabyCharles/frame/databases/mysql"
	"gorm.io/gorm"
)

type Goods struct { //todo:商品表
	gorm.Model
	Title  string `gorm:"type:varchar(100)"`
	Img    string `gorm:"type:text"`
	Price  string `gorm:"type:decimal(10,2)"`
	UserId int64  `gorm:"type:int(11)"`
}

func NewGoods() *Goods {
	return new(Goods)
}
func (p *Goods) CreateGoods(goods *Goods) (*Goods, error) {
	err := mysql.DB.Create(&goods).Error
	if err == gorm.ErrRecordNotFound {
		return nil, nil
	}
	return goods, err
}

func (p *Goods) GetGoodsById(goodsId int64) (*Goods, error) {
	var goods = &Goods{
		Model: gorm.Model{ID: uint(goodsId)},
	}
	err := mysql.DB.Where(goods).First(&goods).Error
	return goods, err
}
func (p *Goods) GetsGoods(offset, limit int64) ([]*Goods, int64, error) {
	var goods []*Goods
	var total int64
	err := mysql.DB.Model(p).Offset(int(offset)).Limit(int(limit)).Find(&goods).Error
	err = mysql.DB.Model(p).Count(&total).Error
	if err != nil {
		return nil, 0, err
	}
	return goods, total, err
}

func (p *Goods) UpdateGoods(goods *Goods) (*Goods, error) {
	err := mysql.DB.Where("id = ?", goods.ID).Updates(&goods).Error
	return goods, err
}
func (p *Goods) DeleteGoods(id int64) error {
	err := mysql.DB.Where("id = ?", id).Delete(&p).Error
	return err
}
